import pandas as pd
import numpy as np
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager

if __name__ == "__main__":
    plt.rcParams["font.sans-serif"] = ["SimSong"]
    plt.rcParams["axes.unicode_minus"] = False
    starbucks = pd.read_csv("directory.csv")
    starbucks.head()

    print("星巴克旗下品牌有：\n", starbucks.Brand.value_counts())
    coffee = starbucks[starbucks.Brand == "Starbucks"]
    print("\n", coffee.shape)

    df = starbucks.groupby(["Country"]).size()
    print("全世界一共有多少个国家和地区开设了星巴克门店：", df.size)
    df1 = df.sort_values(ascending=False)
    print("排名前10的国家和地区:\n", df1.head(10))
    print("排名后10的国家:\n", df1.tail(10))

    # 假设黑体字体安装在用户字体库，你可能需要根据实际安装位置修改路径
    font_path = "/Library/Fonts/Arial Unicode.ttf"
    prop = font_manager.FontProperties(fname=font_path)

    plt.rcParams["font.size"] = 15
    plt.rcParams["font.family"] = "SimSong"
    # df1.head(10).plot(kind="bar,rot=0")
    df1.head(10).plot(kind="bar")
    plt.xticks(rotation=0)
    plt.title("星巴克门店数排名前10的国家和地区")
    plt.ylabel("Store Counts")
    plt.xlabel("Countries and Regions")
    plt.text(0.5, 0, "Countries")
    plt.text(0.5, 0, "Countries", fontsize=12, ha="center", va="bottom")
    plt.show()

    count_starbucks_city = coffee.City.value_counts()
    print("星巴克门店数量排名前10的城市:\n", count_starbucks_city.head(10))
    star = starbucks.dropna(how="any", subset=["City"])
    count_starbucks_city = star.City.value_counts()
    print("全世界星巴克门店数量排名前10的城市:\n", count_starbucks_city.head(10))

    # (5)显示拥有星巴克门店数量排名前10的城市
    plt.figure(1, figsize=(8, 6))
    count_starbucks_city = star.City.value_counts()
    city_top10 = count_starbucks_city.head(10)
    city_top10.plot(kind="bar", rot=30)
    plt.title("拥有星巴克门店最多的10个城市")
    plt.ylabel("Store Counts")
    plt.xlabel("City")
    plt.text(0.5, 0, "Cities")
    # plt.text(0.5, 0, "Cities", fontsize=12, ha="center", va="bottom")
    plt.show()

    # （6）按照星巴克门店在中国的分布情况，统计排名前10的城市
    import pinyin

    df = star[star["Country"] == "CN"]
    df1 = df.copy()
    print(df1["City"])
    df1["City"] = df1["City"].apply(lambda x: x.lower())
    df1["City"] = df1["City"].apply(
        lambda x: pinyin.get(x, format="strip", delimiter="")[0:-3]
    )
    df1 = df1.groupby(["City"]).size().sort_values(ascending=False)
    print(df1.head(10))
 
    #绘制柱状图
    import matplotlib.pyplot as plt
    df1.head(10).plot(kind= 'bar',rot= 30)
    plt.title("中国拥有星巴克门店最多的10个城市")
    plt.ylabel("Store Counts")
    plt.xlabel("Cities")
    plt.text(0.5, 0, "Cities")
    plt.show()
    
    #（8）用饼形图显示星巴克门店的经营方式有几种：
    plt.figure(1,figure = (8,6))
    ownership = star ["Ownership Type"].value_counts()
    plt.title("星巴克门店所有权类型")
    ownership.plot(kind="pie")
    plt.show()